// ==UserScript==
// @name         Youtube Set Default Caption Language
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Youtube Set Default Caption Language
// @author       Chen Kangbing
// @match        *://www.youtube.com/watch?v=*
// @match        *://www.youtube.com
// @match        *://www.youtube.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    var pushState = history.pushState;
    var replaceState = history.replaceState;
    history.pushState = function() {
        pushState.apply(history, arguments);
        window.dispatchEvent(new Event('pushstate'));
        window.dispatchEvent(new Event('locationchange'));
    };
    history.replaceState = function() {
        replaceState.apply(history, arguments);
        window.dispatchEvent(new Event('replacestate'));
        window.dispatchEvent(new Event('locationchange'));
    };
    window.addEventListener('popstate', function() {
        window.dispatchEvent(new Event('locationchange'))
    });

    function setCapLang() {
        const player = document.querySelector('#movie_player');
        if (!player) {
            console.warn('Cannot set caption. No #movie_player found on the page.');
            return;
        }
        let languages = player.getOption('captions', 'tracklist', {
            includeAsr: true // Generated caption
        }) || [];
        if (!languages.length) {
            player.toggleSubtitles();
            languages = player.getOption('captions', 'tracklist', {
                includeAsr: true // Generated caption
            }) || [];
            console.log('subtitles was probably not enabled. Enable and got captions:', languages);
        }
        console.log('languages: ', languages);
        const lang_zhHans = languages.find(language => (
            (language.languageCode === 'zh-Hans')
        ));
        const lang_zhHant = languages.find(language => (
            (language.languageCode === 'zh-Hant')
        ));
        const lang_zh = languages.find(language => (
            (language.languageCode === 'zh')
        ));
        const lang_en = languages.find(language => (
            (language.languageCode === 'en' && language.kind != 'asr')
        ));
        const lang_enAsr = languages.find(language => (
            (language.languageCode === 'en' && language.kind === 'asr')
        ));
        const langs = [lang_zhHans, lang_zhHant, lang_zh, lang_en, lang_enAsr];
        const lang = langs.find(l => (l));
        if (lang) {
            player.setOption('captions', 'track', lang);
        }
        else {
            console.log('Preferred languages not found.');
        }
    }

    var lastVid = '';
    function checkVideoChange() {
        //console.log('checking video change');
        const player = document.querySelector('#movie_player');
        if (!player) {
            console.warn('Cannot set caption. No #movie_player found on the page.');
            return;
        }
        var currVid = player.getVideoData().video_id;
        if (currVid != lastVid) {
            console.log('Video ID changed: ', currVid);
            setCapLang();
            lastVid = currVid;
        }
    }

    //setTimeout(setCapLang, 1000);
    setInterval(checkVideoChange, 1000);
    window.addEventListener('locationchange', (info) => setCapLang());
})()